<?php

namespace App\Logic\Member;

use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Output;
use App\Logic\Member\Form\ProfitScoreGroupListForm;
use App\Logic\Member\Form\ProfitScoreListForm;
use App\Logic\Member\Form\ScoreGroupListForm;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitStatisticsModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use EasySwoole\Http\Request;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Redis\Redis;
use Throwable;

class MemberProfitStatisticsService extends BaseCore
{

    use Singleton;

    /**
     * 字典数据
     * @param $data
     * @return Output
     * @throws Exception
     * @throws Throwable
     */
    public function getDict(Request $request) : Output
    {
        $result = [
            'type'   => ArrayHelper::keyArrayToList(MemberProfitStatisticsModel::getTypeDict()),
        ];

        return $this->success($result);
    }

    /**统计前一天收益数据*/
    public function statistics()
    {
        if((date('Hi') - 0) < 10){
            return false;
        }
        /**查询最后一条记录*/
        $result = MemberProfitStatisticsModel::create()->order('id', 'desc')->get();
        if($result){
            $last_date = $result['date'];
            /**如果$last_date是今天,那么每小时执行一次*/
            if($last_date == date('Y-m-d')){//, strtotime('-1 days')
                if((date('i') - 0) > 0){
                    return false;
                }
            }else {
                /**最后一天加一天*/
                $last_date = date('Y-m-d', strtotime('+1 days', strtotime($last_date)));
            }

        }else{
            $last_date = '2025-02-01';
        }

        $table_name = MemberProfitScoreModel::create()->getTableName();

        /**
         * SELECT created_date, user_id, source_id, type, COUNT(1) `c`, SUM(score) `s` FROM ss_member_profit_score WHERE created_date='2024-10-31' AND score>0 AND type IN ('USERPROFIT', 'REFFERERPROFIT') GROUP BY created_date, user_id, source_id, type;
         * */
        $sql = "SELECT created_date, user_id, source_id, type, COUNT(1) `total`, SUM(score) `amount` FROM {$table_name} WHERE `created_date`='". $last_date ."' AND score>0 AND type IN ('USERPROFIT', 'REFFERERPROFIT') GROUP BY created_date, user_id, source_id, type ";

        $queryBuild = new QueryBuilder();
        $queryBuild->raw($sql);
        $result = DbManager::getInstance()->query($queryBuild, true);
        $total_order_amount = $total_count = 0;
        $data = [];
        if ($result->getResult()) {
            foreach ($result->getResult() as $item) {
                $data[] = [
                    'idx_key'   => $last_date . '-' . $item['user_id'] . '-' . $item['source_id'] . '-' . $item['type'],
                    'date'      => $last_date,
                    'user_id'   => $item['user_id'],
                    'source_id' => $item['source_id'],
                    'type'      => $item['type'],
                    'total'     => $item['total'],
                    'amount'    => $item['amount'],
                ];
            }
        }
        if(empty($data)){
            /**如果没有统计数据,那么写一条空数据进去,防止重复执行*/
            $idx_key = $last_date . '-0-0-USERPROFIT';
            $data[] = [
                'date'      => $last_date,
                'idx_key'   => $idx_key,
                'user_id'   => 0,
                'source_id' => 0,
                'type'      => 'USERPROFIT',
                'total'     => 0,
                'amount'    => 0,
            ];
            MemberProfitStatisticsModel::create()->connection('write')->destroy(['idx_key' => $idx_key]);
        }else{
            $ids = array_column($data, 'idx_key');
            MemberProfitStatisticsModel::create()->connection('write')->destroy(['idx_key' => [$ids, 'in']]);
        }
        MemberProfitStatisticsModel::insertMulti($data);
        return true;
    }

    /**按用户统计收益*/
    public function statisticsByUser($userId)
    {
        $total_user_amount = $total_user_count = $total_referrer_amount = $total_referrer_count = 0;
        $sql = "SELECT user_id, type, SUM(total) `total`, SUM(amount) `amount` FROM `ss_member_profit_statistics` WHERE user_id={$userId} GROUP BY type";
        $queryBuild = new QueryBuilder();
        $queryBuild->raw($sql);
        $result = DbManager::getInstance()->query($queryBuild, true);
        if ($result->getResult()) {
            foreach ($result->getResult() as $item){
                switch ($item['type']){
                    case MemberProfitScoreModel::TYPE_USER_PROFIT:
                        $total_user_count = $item['total'];
                        $total_user_amount = $item['amount'];
                        break;
                    default:
                        $total_referrer_count = $item['total'];
                        $total_referrer_amount = $item['amount'];
                        break;
                }
            }
        }

        return [
            'total_user_amount'     => $total_user_amount,
            'total_user_count'      => $total_user_count,
            'total_referrer_amount' => $total_referrer_amount,
            'total_referrer_count'  => $total_referrer_count
        ];
    }

}
